package com.talkweb.baselibrary.utils;

import ohos.app.Context;
import ohos.data.DatabaseHelper;
import ohos.data.preferences.Preferences;

import java.lang.ref.WeakReference;

/**
 * @author SUQI
 * @date 2020/12/24
 * @description Preferences存储简单数据
 **/
public class PreferencesUtils {

    private static volatile PreferencesUtils instance = null;
    private Preferences preferences = null;
    private static final String NAME = "ishare.db";

    private PreferencesUtils(Context context) {
        DatabaseHelper helper = new DatabaseHelper(new WeakReference<>(context).get());
        preferences = helper.getPreferences(NAME);
    }

    public static PreferencesUtils getInstance(Context context) {
        if (instance == null) {
            synchronized (PreferencesUtils.class) {
                if (instance == null) {
                    instance = new PreferencesUtils(context);
                }
            }
        }
        return instance;
    }

    /**
     * 清除所有数据
     */
    public boolean clear() {
        preferences.clear();
        return preferences.flushSync();
    }

    /**
     * 删除单个数据
     *
     * @param key
     */
    public boolean delete(String key) {
        preferences.delete(key);
        return preferences.flushSync();
    }

    /**
     * 存储数据到preferences
     *
     * @param key
     * @param value
     */
    public boolean putToPreferences(String key, boolean value) {
        preferences.putBoolean(key, value);
        return preferences.flushSync();
    }

    public boolean putToPreferences(String key, String value) {
        preferences.putString(key, value);
        return preferences.flushSync();
    }

    public boolean putToPreferences(String key, int value) {
        preferences.putInt(key, value);
        return preferences.flushSync();
    }

    public boolean putToPreferences(String key, float value) {
        preferences.putFloat(key, value);
        return preferences.flushSync();
    }

    public boolean putToPreferences(String key, long value) {
        preferences.putLong(key, value);
        return preferences.flushSync();
    }

    /**
     * 从preferences获取数据
     *
     * @param key
     * @param defaultVault
     * @return
     */
    public int getInt(String key, int defaultVault) {
        return preferences.getInt(key, defaultVault);
    }

    public long getLong(String key, long defaultVault) {
        return preferences.getLong(key, defaultVault);
    }

    public float getFloat(String key, float defaultVault) {
        return preferences.getFloat(key, defaultVault);
    }

    public String getString(String key, String defaultVault) {
        return preferences.getString(key, defaultVault);
    }

    public boolean getBoolean(String key, boolean defaultVault) {
        return preferences.getBoolean(key, defaultVault);
    }
}
